<template>
  <BasicModal
    title="重新设定密码"
    :width="800"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { message } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { userPasswordFormSchemas } from '../user.data';
  import { updatePawssword } from '/@/api/sys/user';

  const emit = defineEmits(['register', 'success']);

  const recordId = ref('');

  const [registerForm, { setFieldsValue, getFieldsValue, validate, clearValidate, updateSchema }] = useForm({
    schemas: userPasswordFormSchemas,
    showActionButtonGroup: false,
  });

  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    recordId.value = data.record.accountId;
    await setFieldsValue({
      username: data.record.username,
      password: '',
      confirmpassword: '',
    });
    clearValidate();
  });

  const handleSubmit = async () => {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      await updatePawssword({
        id: recordId.value,
        ...values,
      });
      message.success('重置密码成功');
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };

  const handleCancel = () => {
    closeModal();
  };
</script>
